package com.logic.saas.service.security;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.logic.saas.dto.RegisterDTO;
import com.logic.saas.enums.SessionKey;
import com.logic.saas.exception.ValidationException;
import com.logic.saas.persistence.AddressMapper;
import com.logic.saas.persistence.OrganizationMapper;
import com.logic.saas.persistence.UserMapper;
import com.logic.saas.pojo.Ps;
import com.logic.saas.pojo.User;
import com.logic.saas.service.BaseService;
import com.logic.saas.util.AddLog;
import com.logic.saas.util.PojoUtil;

@Service
public class UserService extends BaseService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private OrganizationMapper organizationMapper;
	@Autowired
	private AddressMapper addressMapper;

	public User getUserById(Integer id) throws Exception {
		User user = null;
		
		return user;

	}
	public User findUserByNamePsw(String userName, String password) throws Exception {
		User user = null;
		if(StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)){
			Map<String, Object> par = new HashMap<String, Object>();
			par.put("userName", userName);
			par.put("password", password);
			user = userMapper.getUserByNameAndPsw(new Ps(par));
		}else{
			AddLog.addToLog(this.getClass(), AddLog.ERROR, "user name or password is empty");
			throw new ValidationException("user name or password is empty");
		}
		return user;
	}
	
	@Transactional
	public void register(Integer id,RegisterDTO registerdto) throws Exception {
		if(null != registerdto.getUser() &&  null != registerdto.getOrg()){
			
			//user
			Map<String, Object> userParam = new HashMap<String, Object>();
			//organization
			Map<String, Object> orgParam = new HashMap<String, Object>();
			//organization-address
			Map<String, Object> addressParam = new HashMap<String, Object>();
			//user-organization
			Map<String, Object> userOrgParam = new HashMap<String, Object>();
			
			PojoUtil.setCommonInfo(id, registerdto.getUser());
			PojoUtil.setCommonInfo(id, registerdto.getOrg());
			PojoUtil.setCommonInfo(id, registerdto.getOrg().getAddress());
			userParam.put("user", registerdto.getUser());
			userMapper.insertUser(new Ps(userParam));
			
			addressParam.put("address", registerdto.getOrg().getAddress());
			addressMapper.inserAddress(new Ps(addressParam));
			
			orgParam.put("org", registerdto.getOrg());
			organizationMapper.insertOrg(new Ps(orgParam));
			
			userOrgParam.put("userOrg", registerdto);
			userMapper.insertUserOrg(new Ps(userOrgParam));
		}else{
			AddLog.addToLog(this.getClass(), AddLog.ERROR, "user or organization is empty");
			throw new ValidationException("user or organization is empty");
		}
	}
	
	
}
